package com.na.game.opengl;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.graphics.Typeface;
import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.Renderer;

import com.na.game.GameActivity;
import com.na.game.GameEntity;
import com.na.game.GameMain;
import com.na.game.GameManager;
import com.na.game.ui.UIManager;
import com.na.game.util.GameConfig;

public class GLGameMain extends GameMain implements Renderer {

	private boolean onDrawOver, requestedRender;
	public static GL10 lastGL;
	
	public GLGameMain(GameActivity context, GLSurfaceView view) {
		super(context, view);
	}

	@Override
	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		gl.glClearColor(0.0f, 0.0f, 0.0f, 1f);
    	gl.glShadeModel(GL10.GL_SMOOTH);
    	gl.glClearDepthf(1.0f);
    	gl.glEnable(GL10.GL_DEPTH_TEST);
    	gl.glDepthFunc(GL10.GL_LEQUAL);
    	gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
     	gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
    	gl.glEnable(GL10.GL_BLEND);
    	
    	GLGraphics g = new GLGraphics(context.getGameEntity().invoke(GameEntity.FUNC_GET_DEFAULT_FONT, Typeface.class));
    	g.setScale(scale);
    	g.translate(paintOffsetX, paintOffsetY);
    	graphics = g;
    	start();
	}

	@Override
	public void onSurfaceChanged(GL10 gl, int width, int height) {
		GameConfig.screenWidth = width;
		GameConfig.screenHeight = height;
		gl.glViewport(0, 0, width, height);
        gl.glMatrixMode(GL10.GL_PROJECTION);
        gl.glLoadIdentity();
        gl.glOrthof(0, width, -height, 0, 1, -1);
        gl.glMatrixMode(GL10.GL_MODELVIEW);
        gl.glLoadIdentity();
	}

	@Override
	public void onDrawFrame(GL10 gl) {
		lastGL = gl;
		gl.glClearColor(0f, 0f, 0f, 1f);
    	gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
    	
		gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		
		try {
			((GLGraphics) graphics).drawAll(gl);
		} catch (Exception e) {
			e.printStackTrace();
		}

		gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
    	gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    	
    	onDrawOver = requestedRender;
    	
    	synchronized (this) {
    		try {
    			notify();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
		}
	}

	@Override
	protected void repaint() {
		onDrawOver = false;
		GLGraphics g = (GLGraphics) graphics;
		g.clear();
		GameManager.get(UIManager.class).paint(g);
		((GLSurfaceView) view).requestRender();
		requestedRender = true;
		synchronized (this) {
			try {
				if (!onDrawOver) {
					wait();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void destroy() {
		super.destroy();
		GLTextureManager.destroy(lastGL);
		GLBufferManager.destroy();
	}

}
